package pers.zff.web.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pers.zff.web.common.Constants;
import pers.zff.web.common.MessageInfo;
import pers.zff.web.dao.UserMapper;
import pers.zff.web.po.UserPo;
import pers.zff.web.service.UserService;
import pers.zff.web.util.EmailUtil;
import pers.zff.web.util.PerUtil;

@Service
public class UserServiceImpl implements UserService {

	private static final Log LOG = LogFactory.getLog(UserServiceImpl.class);

	@Autowired
	private UserMapper userMapper;

	@Override
	public UserPo userLogin(UserPo userpo) {
		UserPo userLogin = userMapper.userLogin(userpo);
		return userLogin;
	}

	@Override
	public int userRegister(UserPo userpo) {
		UserPo newUserPo = new UserPo();
		newUserPo.setUserName(userpo.getUserName());
		newUserPo.setUserPassword(userpo.getUserPassword());
		newUserPo.setCreateBy(1L);
		newUserPo.setCreateDate(new Date());
		newUserPo.setMarkForDelete(false);
		return userMapper.insert(newUserPo);
	}

	@Override
	public UserPo fetchUserPoByName(String userName) {
		return userMapper.fetchUserPoByName(userName);
	}

	@Override
	public int saveUserInfoByUpdatePwd(Long userId, UserPo userpo, int randomNum, Date lastSendRandomTime) {
		UserPo newUserPo = new UserPo();
		newUserPo.setUserId(userId);
		newUserPo.setUserEmail(userpo.getUserEmail());
		newUserPo.setRandomText((long) randomNum);
		newUserPo.setLastSendRandomTime(lastSendRandomTime);
		newUserPo.setUpdateBy(1L);
		newUserPo.setUpdateDate(lastSendRandomTime);
		return userMapper.updateByPrimaryKeySelective(newUserPo);
	}

	@Override
	public int updatePwd(Long userId, UserPo userpo) {
		UserPo newUserPo = new UserPo();
		Date currtTime = new Date();
		newUserPo.setUserId(userId);
		newUserPo.setUserPassword(userpo.getUserPassword());
		newUserPo.setUpdateBy(1L);
		newUserPo.setUpdateDate(currtTime);
		return userMapper.updateByPrimaryKeySelective(newUserPo);
	}

	@Override
	public MessageInfo sendEmail(Map<String, Object> map, Date lastSendRandomTime, UserPo userpo,
			MessageInfo messageInfo) {
		int randomNum = PerUtil.getRandomNum(5);
		UserPo user = (UserPo) map.get("userInfo");
		int result = this.saveUserInfoByUpdatePwd(user.getUserId(), userpo, randomNum, lastSendRandomTime);
		if (result == Constants.Integer_one) {
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("receiveMailAccount", userpo.getUserEmail());
			paramMap.put("randomText", randomNum);
			paramMap.put("lastSendRandomTime", lastSendRandomTime);
			boolean sendEmail = EmailUtil.sendEmail(paramMap);
			if (sendEmail) {
				messageInfo.putMessage("发送成功，请查收");
				return messageInfo;
			}
		}
		return messageInfo;
	}

}
